<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ForgotPass extends CI_Controller {
	
	public function index()
	{
		$this->lang->load('site', get_lang());
		$data['page'] = 'pages/forgotpass';
		$this->load->view('mainview', $data);
	}
	
	public function send()
	{
		$posted = $this->input->post();
		
		$data = array(
		   'vl_rescuecode' => rand(1000000000, 9999999999) ,
		);
		
		$this->db->where('nm_email', $posted['email']);
		$this->db->update('users', $data);
		
		$query = $this->db->get_where('users', array('vl_rescuecode' =>$data['vl_rescuecode']));
		$result =$query->result();
		if($result){
			$this->sendMail($result[0]->nm_user, $result[0]->nm_email, $data['vl_rescuecode']);
		}
		
		$this->lang->load('site', get_lang());
		$data['sended'] = true;
		$data['page'] = 'pages/forgotpass';
		$this->load->view('mainview', $data);
		
	}
	
	public function rescue($cod)
	{	
		$this->db->select('id_user, nm_user, nm_email');
		$this->db->from('users');
		$this->db->where('vl_rescuecode', $cod);
		$query = $this->db->get();
		
		$this->lang->load('site', get_lang());
		$result = $query->result();
		if($result){
			$data['user'] = $result[0];
			$data['rescuecode'] = $cod;
			$data['page'] = 'pages/rescuepass';
		}else{
			$data['page'] = 'pages/rescuepasserror';
		}
		$this->load->view('mainview', $data);
		
	}
	
	public function restore()
	{
		$posted = $this->input->post();
		
		$this->lang->load('site', get_lang());
		if($posted['pass'] == $posted['repass']){			
			$data = array('vl_rescuecode' => NULL, 'nm_pass' => md5($posted['pass']));
			$this->db->where('vl_rescuecode', $posted['rescuecode']);
			$this->db->update('users', $data);
			
			$data['confer'] = true;
			$data['page'] = 'pages/rescueok';
			$this->load->view('mainview', $data);
		}else{
			$data['passerror'] = true;
			$data['page'] = 'pages/rescuepasserror';
			$this->load->view('mainview', $data);
		}
	}
	
	public function sendMail($name, $email, $rescuecode){
	
		
		$this->load->library('email');
	
		$config['protocol'] = 'sendmail';
		$config['mailpath'] = '/usr/sbin/sendmail';
		$config['mailtype'] = 'html';
		$config['charset'] = 'utf-8';
		$config['useragent'] = 'wedesignclothing';
		$config['wordwrap'] = TRUE;
	
		$message = $this->load->view('email/rescuepass', array('name'=>$name, 'rescuecode'=>$rescuecode), TRUE);
		//echo ($message);
		//exit;
		
		$this->email->initialize($config);
		$this->email->from('talkwith@wdcloth.com', 'We Design Clothing Team');
		$this->email->to($email);
		$this->email->subject('Recuperação de senha');
		$this->email->message($message);
		$this->email->send();
	}
}
